from ocw.ntu.models import Teacher, Course, DailyQuote
from django.db.models import Q
from django.template import Context, loader
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import Http404
import random

# Create your views here.

# TODO: Refactoring (simplify with redirect_to_response)
def index(request):
    latest_course_list = Course.objects.all().order_by('-publishDate')[:5]
    dailyQuoteList = DailyQuote.objects.all().order_by('-publishDate')[:5]
    if len(dailyQuoteList) == 0:
        dailyQuote = None
    else:
        ddailyQuote = random.choice(dailyQuoteList)

    t = loader.get_template('ntu/index.html')
    c = Context({
        'latest_course_list': latest_course_list,
	'daily_quote': dailyQuote,
	
    })
    return HttpResponse(t.render(c))

def search(request):
    query = request.GET.get('q', '')
    if query:
        qset = (
            Q(nameEN__icontains=query) |
            Q(courseDescription__icontains=query) |
            Q(courseAbstract__icontains=query) |         
            Q(nameZH__icontains=query)
        ) 
        results = Course.objects.filter(qset)
    else:
        results = []
    return render_to_response("courses_search.html", {
        "results": results,
        "query": query
    })
    
def course_detail(request):
    try:
        course = Course.objects.latest('publishDate')
    except Course.DoesNotExist:
        raise Http404
    return render_to_response(
        'ntu/comments.html', {'course' : course},
        context_instance = RequestContext(request)
    )


#    try:
#        course = Course.objects.latest('publishDate')
#    except BlogPost.DoesNotExist:
#        raise Http404
#    return render_to_response(
#        'blog/latest_post.html', {'post' : post},
#        context_instance = RequestContext(request)

from django import http
from django import newforms as forms
from django.shortcuts import render_to_response
#from django.settings import MEDIA_ROOT
from django.conf import settings

class SimpleFileForm(forms.Form):
    file = forms.Field(widget=forms.FileInput, required=False)
 
def video_upload(request):
    """
    Saves the file directly from the request object. 
    Disclaimer:  This is code is just an example, and should
    not be used on a real website.  It does not validate
    file uploaded:  it could be used to execute an 
    arbitrary script on the server. 
    """
 
    template = 'upload.html'
 
#    return render_to_response(template)

    if request.method == 'POST':
        if 'file' in request.FILES:
            file = request.FILES['file']
            return render_to_response(template)
         
            try: 
	            # Other data on the request.FILES dictionary:
		         #   filesize = len(file['content'])<br />
		         #   filetype = file['content-type'] 

		          filename = file['filename']
	 
		          fd = open('%s/%s' % (settings.MEDIA_ROOT, filename), 'wb')
		          fd.write(file['content'])
		          fd.close()
                
#return render_to_response(template)
		          
                #return http.HttpResponseRedirect('upload.html')
            except Error:
                raise Http404

    else:
        # display the form
        form = SimpleFileForm()
        return render_to_response(template, { 'form': form })
 

